package com.zhaosc.elasticsearch;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.elasticsearch.action.DocWriteResponse.Result;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.junit.Test;

import com.google.common.collect.Maps;

/**
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.5/java-rest-high-document-update.html
 * 
 * @author zhaosc
 *
 */
public class UpdateTest extends BaseTest {

	private static final Logger logger = Logger.getLogger(UpdateTest.class);

	/**
	 * 利用脚本更新
	 */
	@Test
	public void testUpdate01() {
		UpdateRequest updateRequest = new UpdateRequest(index, "1");

		// 1.inline script,增加字段
		Map<String, Object> parameters = Maps.newHashMap();
		parameters.put("count", 5);
		Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.count= params.count", parameters);
		updateRequest.script(inline);

		// 2.stored script，scriptdemo是es上的脚本名称
//		Script stored = new Script(
//		        ScriptType.STORED, null, "scriptdemo", parameters);  
//		updateRequest.script(stored); 

		try {

			UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * json字符串 文档字段
	 */
	@Test
	public void testUpdate02() {
		UpdateRequest request = new UpdateRequest(index, "1");
		String jsonString = "{" + "\"updated\":\"2019-12-12\"," + "\"reason\":\"daily update\"" + "}";
		request.doc(jsonString, XContentType.JSON);
		try {

			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error("",e);
		}
	}

	/**
	 * Map 形式
	 */
	@Test
	public void testUpdate03() {
		Map<String, Object> jsonMap = Maps.newHashMap();
		jsonMap.put("updated", new Date());
		jsonMap.put("reason", "daily update");
		UpdateRequest request = new UpdateRequest(index, "1").doc(jsonMap);

		try {
			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * XContentBuilder 形式
	 */
	@Test
	public void testUpdate04() {

		try {
			XContentBuilder builder = XContentFactory.jsonBuilder();
			builder.startObject();
			{
				builder.timeField("updated", new Date());
				builder.field("reason", "daily update 1");
			}
			builder.endObject();
			UpdateRequest request = new UpdateRequest(index, "1").doc(builder);
			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * key -value形式
	 */
	@Test
	public void testUpdate05() {
		UpdateRequest request = new UpdateRequest(index, "1").doc("updated", new Date(), "reason", "daily update2");
		try {
			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * 当文档存在时，执行脚本；当文档不存在时，创建新文档，并将upsert中的内容就会插入到对应的文档中
	 */
	@Test
	public void testUpset01() {
		UpdateRequest request = new UpdateRequest(index, "2");
		String jsonString = "{\"created\":\"2017-01-01\"}";
		Map<String, Object> parameters = Maps.newHashMap();
		parameters.put("count", 10000);
		Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.count= params.count", parameters);
		request.script(inline);
		request.upsert(jsonString, XContentType.JSON); 

		try {
			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
			if (Result.UPDATED == updateResponse.getResult()) {
				logger.info("***success***");
			} else {
				logger.info("***fail***");
			}
		} catch (IOException e) {
			logger.error(e);
		}
	}

}
